package com.xbai.oauth.util;

import org.assertj.core.util.Arrays;
import org.springframework.security.core.parameters.P;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jxbai
 * @desc
 * @date 2021/2/5 0005
 */
public class CookieUtil {

    /**
     * 设置cookie
     * @param response {@link HttpServletResponse}
     * @param domain 域名
     * @param path 路径
     * @param name cookie名字
     * @param value cookie值
     * @param maxAge cookie生命周期 以秒为单位
     * @param httpOnly 是否仅支持http
     */
    public static void addCookie(HttpServletResponse response, String domain, String path,
                                 String name, String value, int maxAge, boolean httpOnly) {
        Cookie cookie = new Cookie(name, value);
        cookie.setDomain(domain);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        cookie.setHttpOnly(httpOnly);
        response.addCookie(cookie);
    }

    /**
     * 根据cookie名称读取cookie
     * @param request {@link HttpServletRequest}
     * @param cookieNames cookie名称
     * @return cookie集合
     */
    public static Map<String,String> readCookie(HttpServletRequest request, String ... cookieNames) {
        Map<String,String> cookieMap = new HashMap<>(cookieNames.length);
        Cookie[] cookies = request.getCookies();
        if (Arrays.isNullOrEmpty(cookies)) {
            return cookieMap;
        }
        for (Cookie cookie : cookies) {
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            for (String name : cookieNames) {
                if (name.equals(cookieName)) {
                    cookieMap.put(cookieName, cookieValue);
                }
            }
        }
        return cookieMap;
    }
}
